package cn.fl.project.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdPaySchTMQC;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPrdBscInfoService;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdDtlTkService;
import cn.fl.project.service.IPrjPrdPaySchTMService;
import cn.fl.project.service.IPrjQuatPrpsCfgMService;
import cn.fl.project.service.IPrjQuatPrpsService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPrdBscInfoVO;
import cn.fl.project.vo.PrjPrdDtlTkVO;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdPaySchDVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.project.vo.PrjPrdPaySchTMVO;
import cn.fl.project.vo.PrjPrdPrpsFeeDetailVO;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @Description: 项目产品支付表主信息表（挂靠公司版） 控制层
 */
@Controller
@RequestMapping("/project/prjPrdPaySchTM")
public class PrjPrdPaySchTMController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PrjPrdPaySchTMController.class);

	/**
	 * PrjPrdPaySchTM 服务层BEAN
	 */
	@Autowired
	private IPrjPrdPaySchTMService prjPrdPaySchTMService;
	
	@Autowired
    private IPrjPrdDtlService prjPrdDtlService;
	
	@Autowired
    private IPrjBscInfoService prjBscInfoService;

	@Autowired
    private IPrjPrdBscInfoService prjPrdBscInfoService;
	
	@Autowired
    private IPrjPrdDtlTkService prjPrdDtlTkService;
	
	@Autowired
	private IPrjQuatPrpsCfgMService prjQuatPrpsCfgMService;
	
	@Autowired
	private IPrjQuatPrpsService prjQuatPrpsService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjPrdPaySchTM/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("project/prjPrdPaySchTM/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjPrdPaySchTMQC qc = new PrjPrdPaySchTMQC();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();//this.prjPrdPaySchTMService.searchListPage(page);
		List<PrjPrdPaySchTMVO> list = (List<PrjPrdPaySchTMVO>) pager.getResultList();
		ListPageVO<PrjPrdPaySchTMVO> listPage = new ListPageVO<PrjPrdPaySchTMVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjPrdPaySchTMService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	/**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载PrjPrdPaySchM Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("project/prjprdquatprps/prjPrdQuatPrpsAddForClx");
        String prjPrdDtlId = request.getParameter("prjPrdDtlId");//项目商品明细ID
        String prjId = request.getParameter("prjId");//项目ID
        String prjPrdId = request.getParameter("prjPrdId");
        String id = request.getParameter("id");
        String detailFlag = request.getParameter("detailFlag");
    	//费用类型
		JSONArray feeTypCdListJSON = this.prjQuatPrpsCfgMService.searchFeeTypCdList();
		mav.addObject("feeTypCdListJSON", feeTypCdListJSON);
		//费用计算基数
		List<KeyValueVO> calBaseCdList = this.prjQuatPrpsCfgMService.searchCalBaseCdList();
		if(CollectionUtils.isNotEmpty(calBaseCdList)){
			for (int i=0; i<calBaseCdList.size();i++) {
				if(calBaseCdList.get(i).getKey().equals(PrjQuatPrpsConstant.CODE_CAL_BASE_CONTRACT)){
					calBaseCdList.remove(i);
				}
			}
		}
		mav.addObject("calBaseCdListJSON", JSON.toJSONString(calBaseCdList));
		List<KeyValueVO> yesNoCdList = this.prjQuatPrpsCfgMService.searchYesOrNoCdList();
		mav.addObject("yesOrNoCdListJSON",JSON.toJSONString(yesNoCdList) );
		//费用计入方式
		List<KeyValueVO> cntWayCdList = this.prjQuatPrpsCfgMService.searchCntWayCdList();
		Map<String,String>  scaleNumMap  =  this.prjQuatPrpsService.getDecimalDigitsByBuOrgCode();
		if(CollectionUtils.isNotEmpty(cntWayCdList)){
			for (int i=0; i<cntWayCdList.size();i++) {
				if(cntWayCdList.get(i).getKey().equals(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CNT_WAY_FINANC)){
					cntWayCdList.remove(i);
				}
			}
		}
		//计算方式
	   mav.addObject("cntWayCdListJSON", JSON.toJSONString(cntWayCdList));
       mav.addObject("prjId", prjId);
       mav.addObject("prjPrdDtlId", prjPrdDtlId);
       mav.addObject("prjPrdId", prjPrdId);
       mav.addObject("id", id);
       mav.addObject("detailFlag", detailFlag);
       mav.addObject("scaleNumMap", scaleNumMap.isEmpty()==true?"":JSON.toJSONString(scaleNumMap));
        return mav;
    }

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        String prjId = request.getParameter("prjId");
        String prjPrdId = request.getParameter("prjPrdId");
        String prjPrdDtlId = request.getParameter("prjPrdDtlId");
        if(StringUtils.isNotBlank(prjPrdDtlId) && StringUtils.isBlank(prjPrdId)){
            PrjPrdDtlVO vo = prjPrdDtlService.selectById(Long.valueOf(prjPrdDtlId));
            if(vo != null){
                prjPrdId = String.valueOf(vo.getPrjPrdId());
            }
        }
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        PrjPrdPaySchMVO vo = null;
        try {
        	vo = this.prjPrdPaySchTMService.selectPrjPrdPaySchTMAndDetailById(Long.valueOf(id));
            if (null == vo) {
            	result.setSuccess(BaseConstant.IS_YESNO_NO);
            	result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
            	BaseLogUtils.info(logger, "getPrjPrdPaySchMById", "获取PrjPrdPaySchM数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            PrjBscInfoVO prjBsc  = this.prjBscInfoService.selectById(Long.valueOf(prjId));
            PrjPrdBscInfoVO prjPrdBsc = this.prjPrdBscInfoService.selectById(Long.valueOf(prjPrdId));
            if(null!=prjPrdBsc.getGuidePc()){
            	prjPrdBsc.setGuidePc(DecimalUtils.convertFenToYuan(prjPrdBsc.getGuidePc().longValue()));
            }
            vo.setPrjBscInfo(prjBsc);
            vo.setPrjPrdBscInfo(prjPrdBsc);
            
            if(StringUtils.isNotBlank(prjPrdDtlId)){
            	PrjPrdDtlTkVO tk = this.prjPrdDtlTkService.selectById(Long.valueOf(prjPrdDtlId));
            	PrjPrdDtlVO dtlVO = this.prjPrdDtlService.selectById(Long.valueOf(prjPrdDtlId));
            	if (null!=dtlVO) {
					vo.setDtlVO(dtlVO);
				}
            	if(null!=tk){
            		vo.setDtlTkVO(tk);
            	}
            }
            
            if(CollectionUtils.isNotEmpty(vo.getPrjPrdPayDetailList())){
                  ListPageVO<PrjPrdPrpsFeeDetailVO> listPage = new ListPageVO<PrjPrdPrpsFeeDetailVO>(vo.getPrjPrdPayDetailList(), vo.getPrjPrdPayDetailList().size());
            	vo.setPrjQuatPrpsPaySchPage(listPage);
            }
            if(CollectionUtils.isNotEmpty(vo.getFeeDetailList())){
                ListPageVO<PrjPrdPaySchDVO> listPage = new ListPageVO<PrjPrdPaySchDVO>(vo.getFeeDetailList(), vo.getFeeDetailList().size());
                vo.setFeeDetailListPage(listPage);
          }
            result.setData(vo);
            BaseLogUtils.info(logger, "getPrjPrdPaySchMById", "获取PrjPrdPaySchM数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getPrjPrdPaySchMById", "获取PrjPrdPaySchM数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getPrjPrdPaySchMById", "获取PrjPrdPaySchM数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjPrdPaySchTMVO entity = null;
		try {
			entity = new PrjPrdPaySchTMVO();
			//TODO ADD PARAM
			Long id = this.prjPrdPaySchTMService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PrjPrdPaySchTMVO entity = null;
		try {
			entity = new PrjPrdPaySchTMVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.prjPrdPaySchTMService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

